/*
 * Based on jQuery Plugin spy (leftlogic.com/info/articles/jquery_spy)
 * (c) 2006 Remy Sharp (leftlogic.com) jquery[at]leftlogic[dot]com
 * $Id: spy.js,v 1.2 2006/08/14 10:07:18 remy Exp $
 * 
 * Used for Cinnamon Statistics Engine
 */

$.fn.spy = function(settings) {
	if (!settings['ajax']) {
		alert("An AJAX/AJAH URL must be set for the spy to work.");
		return;
	}
	
	var o = {
		limit: (settings['limit'] || 10),
		fadeLast: (settings['fadeLast'] || 5),
		ajax: settings['ajax'],
		timeout: (settings['timeout'] || 5000),
		fadeInSpeed: (settings['fadeInSpeed'] || 'slow')
	};
	
	
	//var current = "";
	return this.each(function() {
		var e = this;
		var timestamp = Date.parse( new Date() ) / 1000;
		e.timer = window.setInterval(function() {
			$.post(o['ajax'], { csemode: 'ajax', component: e.id, 'timestamp': timestamp }, function(r) {	

				$('#' + e.id + ' div.content table tbody tr:gt(' + (o['limit'] - 2) + ')').remove();
				$('#' + e.id + ' div.content table tbody tr:gt(' + (o['limit'] - o['fadeLast'] - 2) + ')').fadeEachDown();
				
				
				var rows = r.substr( ( r.indexOf('<tbody>') + '<tbody>'.length ) );
				rows = rows.substr(0, rows.indexOf('</tbody>') );
				
				$('#'+ e.id +' div.content table tbody').html( rows + $('#'+ e.id +' div.content table tbody').html() );  
				
				/*
				FADE IN IMPLEMENTATION - UNDER DEVELOPMENT
				$('#'+ e.id +' div.content table.zebra tbody tr:first').addClass('topElement');
				first = $('#'+ e.id +' div.content table.zebra tbody tr.topElement').html();
				
				if (first!=current){
					first = current; 
				} else {
					$('#'+ e.id +' div.content table.zebra tbody tr.topElement').fadeIn(o['fadeInSpeed']);
					//$('#'+ e.id +' div.content table.zebra tbody tr.topElement').width("1000px");
					//$('#'+ e.id +' div.content table.zebra tbody tr:first').html(first);
				}
				*/
				
				$('#'+ e.id +' div.content table.zebra tbody tr').removeClass('alt');
				$('#'+ e.id +' div.content table.zebra tbody tr:nth-child(odd)').addClass('alt');
				
				
			});
		    timestamp = Date.parse( new Date() ) / 1000;
		}, o['timeout']);
	});
};

$.fn.fadeEachDown = function() {
	var s = this.size();
	return this.each(function(i) {
		var o = 1 - (s == 1 ? 0.5 : 0.85/s*(i+1));
		var e = this.style;
		e.opacity = o;
	});
};

$(document).ready( function() {
	$('div#Spy').spy( {
		limit:20, fadeLast: 5, ajax: './spy.php', fadeInSpeed: 500
	} );
} );